<template>
  <view class="app bg">
    <view class="main-top">
      <image mode="aspectFit" src="@/static/image/login.svg" class="absolute banner w-full"></image>
    </view>
    <view class="main-body">
      <view class="input-item">
        <view class="input-title">手机号码</view>
        <view class="input-line">
          <input
            type="text"
            v-model="form.phone"
            placeholder="请输入手机号码"
            placeholder-class="input-placeholder"
            @blur="verifyPhone()"
          />
        </view>
      </view>

      <view class="input-item">
        <view class="input-title">验证码</view>
        <view class="input-line">
          <view class="flex flex-1 overflow-hidden" @click="openKeyborad()">
            <u-message-input
              mode="bottomLine"
              v-model="form.code"
              width="34"
              font-size="28"
              :maxlength="codeMaxlength"
              :breathe="false"
              :disabled-keyboard="true"
            ></u-message-input>
          </view>
          <u-keyboard
            mode="number"
            v-model="showKeyboard"
            :tooltip="false"
            :dot-enabled="false"
            @change="keyboardChange"
            @backspace="keyboardDelete"
          >
            <view class="paste-btn" @click="pasteCode()">粘贴</view>
          </u-keyboard>
          <view class="smscode-btn" :class="{ 'count-down': countActive }" @click="sendVerifyCode()">
            {{ showCodeText }}
          </view>
        </view>
      </view>

      <view class="input-item">
        <view class="input-title">密码</view>
        <view class="input-line">
          <input
            v-model="form.password"
            placeholder="请输入6位以上密码"
            :password="!showPwd"
            @blur="verifyPassword()"
          />
          <u-icon
            name="show-eye"
            custom-prefix="mt-icon"
            size="22"
            v-if="showPwd"
            color="#979797"
            @click="showPwd = !showPwd"
          ></u-icon>
          <u-icon
            name="close-eye"
            custom-prefix="mt-icon"
            size="24"
            v-else
            color="#979797"
            @click="showPwd = !showPwd"
          ></u-icon>
        </view>
      </view>

      <view class="input-item">
        <view class="input-title">重复密码</view>
        <view class="input-line">
          <input
            v-model="form.repassword"
            placeholder="请再次输入密码"
            :password="!showRePwd"
            @blur="verifyRepassword()"
          />
          <u-icon
            name="show-eye"
            custom-prefix="mt-icon"
            size="22"
            v-if="showRePwd"
            color="#979797"
            @click="showRePwd = !showRePwd"
          ></u-icon>
          <u-icon
            name="close-eye"
            custom-prefix="mt-icon"
            size="24"
            v-else
            color="#979797"
            @click="showRePwd = !showRePwd"
          ></u-icon>
        </view>
      </view>

      <view class="input-item">
        <view class="input-title">邀请码<text class="color-red">（必填）</text></view>
        <view class="input-line">
          <input type="text" v-model="form.invite_code" maxlength="6" placeholder="请输入邀请码" />
        </view>
      </view>

      <view class="login-btn" @click="userRegister()">注册</view>
      <view class="login-tips" @click="gotoLogin()">已有账号？前去登录</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { register, sendSmsCaptcha } from '@/api/auth';
  import { useFansStore } from '@/store/fans';
  import { report } from '@/utils/exception';
  import { msg } from '@/utils/msg';
  import { regexpPhone } from '@/utils/regexp';
  import { onLoad } from '@dcloudio/uni-app';
  import { getUrlParams } from '@/utils/funclib';

  const fansStore = useFansStore();
  const showKeyboard = ref<boolean>(false);
  const codeText = '获取验证码';
  const showCodeText = ref<string>(codeText);
  const countActive = ref<boolean>(false);
  const lifeTime = 60;
  let leftTime = lifeTime;
  let codeMaxlength = 6;

  const form = ref({
    phone: '',
    code: '',
    password: '',
    repassword: '',
    invite_code: '',
  });
  const showPwd = ref<boolean>(false);
  const showRePwd = ref<boolean>(false);

  onLoad((options: any) => {
    if (fansStore.fansinfo.token) {
      return uni.switchTab({ url: '/pages/index/index' });
    }

    /* #ifdef H5 */
    if (options['code']) {
      form.value.invite_code = options['code'];
    }
    /* #endif */

    /* #ifdef MP-WEIXIN */
    // 微信小程序扫码获取码信息
    if (options.q) {
      const url = decodeURIComponent(options.q);
      form.value.invite_code = getUrlParams(url, 'code');
    }
    /* #endif */
  });

  const openKeyborad = () => {
    form.value.code = '';
    showKeyboard.value = true;
  };

  const keyboardChange = (val: string) => {
    if (form.value.code.length >= codeMaxlength) return;
    form.value.code += val;
    if (form.value.code.length == codeMaxlength) {
      showKeyboard.value = false;
      userRegister();
    }
  };

  const keyboardDelete = () => {
    if (!form.value.code.length) return;
    form.value.code = form.value.code.substring(0, form.value.code.length - 1);
  };

  const pasteCode = () => {
    uni.getClipboardData({
      success: (res) => {
        if (!/^\d{6}$/.test(res.data)) return;
        form.value.code = res.data;
        showKeyboard.value = false;
        userRegister();
      },
    });
  };

  const verifyPhone = () => {
    if (!form.value.phone) {
      msg.error('请输入手机号码');
      return false;
    }

    if (!regexpPhone(form.value.phone)) {
      msg.error('手机号码格式错误');
      return false;
    }
    return true;
  };

  const sendVerifyCode = () => {
    if (countActive.value) {
      return;
    }

    if (!verifyPhone()) {
      return;
    }

    // 后台发送验证码
    msg.loading('发送中');
    sendSmsCaptcha(form.value.phone, 'register')
      .then((res) => {
        setTimeout(() => {
          msg.success('验证码已发送');
          countActive.value = true;
          showCodeText.value = leftTime + 's';
          openKeyborad();

          let timer = setInterval(() => {
            if (leftTime == 0) {
              leftTime = lifeTime;
              showCodeText.value = codeText;
              countActive.value = false;
              clearInterval(timer);
              return;
            }

            leftTime--;
            showCodeText.value = leftTime + 's';
          }, 1000);
        }, 1000);
      })
      .catch((err) => {
        setTimeout(() => {
          report(err);
        }, 800);
      });
  };

  const verifyPassword = () => {
    if (form.value.password.length < 6) {
      msg.error('请输入6位以上密码');
      return false;
    }
    return true;
  };

  const verifyRepassword = () => {
    if (form.value.password != form.value.repassword) {
      msg.error('两次密码输入不一致');
      return false;
    }
    return true;
  };

  // 注册
  const userRegister = () => {
    if (!verifyPhone()) {
      return;
    }
    if (!form.value.code) {
      return msg.error('请输入验证码');
    }
    if (!verifyPassword()) {
      return;
    }
    if (!verifyRepassword()) {
      return;
    }
    if (!form.value.invite_code) {
      return msg.error('请输入邀请码');
    }

    msg.loading('正在提交');
    register(form.value)
      .then((res) => {
        msg.success('注册成功');
        fansStore.setFansInfo(res.data);
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/index/index' });
        }, 1500);
      })
      .catch((err) => {
        report(err);
      });
  };

  const gotoLogin = () => {
    uni.navigateTo({ url: '/pages/auth/login' });
  };
</script>

<style lang="scss" scoped>
  .bg {
    background: linear-gradient(315deg, #e8ebf8, #eef5f7);
  }

  .main-top {
    .banner {
      top: -230rpx;
    }
  }

  .main-body {
    background: white;
    margin: 21% 40rpx 10%;
    padding: 70rpx 40rpx 60rpx;
    border-radius: 30rpx;
    box-shadow: rgba(64, 64, 64, 0.1) 0px 20px 60px;

    .input-item {
      &:not(:last-child) {
        margin-bottom: 45rpx;
      }
      .input-title {
        font-size: 26rpx;
        font-weight: 600;
        color: #74848c;
        margin-left: 5rpx;
        margin-bottom: 18rpx;
      }

      .input-line {
        display: flex;
        align-items: center;
        background: #eef5f7;
        padding: 0 32rpx;
        height: 96rpx;
        border-radius: 20rpx;

        input {
          font-size: 28rpx;
          font-weight: 600;
          padding-left: 5rpx;
          letter-spacing: 2rpx;
          width: 100%;
        }

        .smscode-btn {
          color: #0851dd;
          font-size: 27rpx;
          width: 165rpx;
          text-align: center;
          margin-left: 20rpx;
          padding-left: 25rpx;
          border-left: 1rpx solid black;
        }

        .count-down {
          color: #8d8d8d;
        }
      }

      .paste-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100rpx;
        border-radius: 12rpx;
        padding: 12rpx 15rpx;
        margin: 12rpx 0 12rpx 30rpx;
        background: #f2f2f2;
      }
    }

    .login-btn {
      color: white;
      letter-spacing: 8rpx;
      background: linear-gradient(315deg, #429ff6, #394eea, #2664ef);
      margin-bottom: 15rpx;
      text-align: center;
      font-weight: 600;
      font-size: 27rpx;
      border-radius: 20rpx;
      padding: 27rpx 0;
    }

    .login-tips {
      font-size: 27rpx;
      margin: 30rpx 5rpx 20rpx 0;
      text-align: right;
    }
  }

  :deep(.input-placeholder) {
    font-weight: 100;
  }
</style>
